package data.socket
{
	import data.events.SocketBaseEvent;
	import flash.events.EventDispatcher;
	public class SocketData extends EventDispatcher
	{
		private var _socketBase:SocketBase;
		private var _socketOut:SocketOut;
		
		public function SocketData()
		{
			_socketBase = new SocketBase();
			_socketOut=new SocketOut();
			setEvent();
		}
		
		/**
		 *设置事件 
		 */		
		private function setEvent():void 
		{
			_socketBase.addEventListener(SocketBaseEvent.CLOSE, handler);  
			_socketBase.addEventListener(SocketBaseEvent.CONNECT, handler);  
			_socketBase.addEventListener(SocketBaseEvent.IO_ERROR, handler);  
			_socketBase.addEventListener(SocketBaseEvent.SECURITY_ERROR, handler);  
			_socketBase.addEventListener(SocketBaseEvent.SENDING, handler);  
			_socketBase.addEventListener(SocketBaseEvent.SOCKET_DATA, handler); 
			_socketBase.addEventListener(SocketBaseEvent.DECODE_ERROR, handler);  
		}
		
		/**
		 *Socket通讯连接 
		 */		
		public function connect(host:String, port:uint):void
		{
			_socketBase.connect(host, port);
		}
		
		/**
		 *事件处理
		 */		
		private function handler(event:SocketBaseEvent):void
		{  
			switch(event.type)
			{
				case SocketBaseEvent.SOCKET_DATA:
					socketReceive(event.data);
					break;
				case SocketBaseEvent.CLOSE:
					socketClose();
					break;
				case SocketBaseEvent.CONNECT:
					socketConnect();
					break;  
				case SocketBaseEvent.IO_ERROR:
				case SocketBaseEvent.SECURITY_ERROR:
				case SocketBaseEvent.DECODE_ERROR:
					break;    
			}
			
			trace("Socket连接状态事件：" + event.type);
		}
		
		/**
		 * Socket数据返回
		 * @param object 数据
		 */
		private function socketReceive(object:Object):void
		{
			dispatchEvent(new SocketBaseEvent(SocketBaseEvent.SOCKET_DATA, object));
		}
		
		/**
		 * Socket已连接
		 */		
		private function socketConnect() : void 
		{
			_socketOut.register(_socketBase, registerCallBack);//Socket发送类注册
		}
		
		/**
		 * Socket连接关闭 
		 */		
		private function socketClose() : void 
		{
			if(_socketOut) _socketOut.dispose();
			_socketOut=null;
		}
		
		/**
		 *Socket对象注册成功后返回 
		 */		
		private function registerCallBack():void
		{
			dispatchEvent(new SocketBaseEvent(SocketBaseEvent.REGISTER_COMPLETE));
		}
		
		/**
		 * Socket外发对象
		 */		
		public function get socketOut():SocketOut
		{
			return _socketOut;
		}
		
		/**
		 *资源释放 
		 */		
		public function dispose():void
		{
			if(_socketBase.connected)
			{
				_socketBase.close();
			}

			if(_socketOut) _socketOut.dispose();
			_socketOut=null;
			_socketBase=null;
		}
	}
}